<template>
  <div class="p-2 container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="uscc" label-width="130px">
              <el-input v-model="queryParams.uscc" placeholder="请输入统一社会信用代码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="责任人" prop="responsiblePeople">
              <el-input v-model="queryParams.responsiblePeople" placeholder="请输入责任人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="queryParams.telephone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['enterprise:enterprise-info:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['enterprise:enterprise-info:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['enterprise:enterprise-info:remove']"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['enterprise:enterprise-info:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar @queryTable="getList" v-model:showSearch="showSearch"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="enterpriseInfoList" height="calc(100% - 30px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="企业名称" align="center" prop="enterpriseName" />
        <el-table-column label="统一社会信用代码" align="center" prop="uscc" />
        <el-table-column label="责任人" align="center" prop="responsiblePeople" />
        <el-table-column label="联系电话" align="center" prop="telephone" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['enterprise:enterprise-info:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['enterprise:enterprise-info:edit']" link type="primary" @click="handleDetails(scope.row)">详情 </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['enterprise:enterprise-info:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业信息对话框 -->
    <el-drawer v-model="dialog.shouAdd" :title="dialog.title" width="500px" append-to-body size="35%">
      <el-form ref="enterpriseInfoFormRef" :model="form" :rules="rules" label-width="135px">
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="uscc">
          <el-input v-model="form.uscc" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="责任人" prop="responsiblePeople">
          <el-input v-model="form.responsiblePeople" placeholder="请输入责任人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicenseImageId">
          <ImageUpload v-model="form.businessLicenseImageId" :limit="1" />
        </el-form-item>
        <el-form-item label="企业LOGO" prop="logoImageId">
          <ImageUpload v-model="form.logoImageId" :limit="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 详情对话框 -->
    <el-drawer v-model="dialog.details" :title="dialog.title" width="500px" append-to-body size="60%">
      <el-form ref="enterpriseInfoFormRef" :model="form" :rules="rules" label-width="135px">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="first">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" disabled />
            </el-form-item>
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" disabled />
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="uscc">
              <el-input v-model="form.uscc" placeholder="请输入统一社会信用代码" disabled />
            </el-form-item>
            <el-form-item label="责任人" prop="responsiblePeople">
              <el-input v-model="form.responsiblePeople" placeholder="请输入责任人" disabled />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入联系电话" disabled />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseImageId">
              <ImageUpload v-model="form.businessLicenseImageId" :limit="1" />
            </el-form-item>
            <el-form-item label="企业LOGO" prop="logoImageId">
              <ImageUpload v-model="form.logoImageId" :limit="1" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="人员信息" name="second">
            <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
              <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                  <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item label="用户名" prop="userName">
                      <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter="handleUserQuery" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                      <el-input v-model="queryParams.gender" placeholder="请输入性别" clearable @keyup.enter="handleUserQuery" />
                    </el-form-item>
                    <el-form-item label="照片" prop="photo">
                      <el-input v-model="queryParams.photo" placeholder="请输入照片" clearable @keyup.enter="handleUserQuery" />
                    </el-form-item>
                    <el-form-item label="证件号码" prop="idCardNo">
                      <el-input v-model="queryParams.idCardNo" placeholder="请输入证件号码" clearable @keyup.enter="handleUserQuery" />
                    </el-form-item>
                    <el-form-item label="车牌号" prop="licensePlateNumber">
                      <el-input v-model="queryParams.licensePlateNumber" placeholder="请输入车牌号" clearable @keyup.enter="handleUserQuery" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleUserQuery">搜索</el-button>
                      <el-button icon="Refresh" @click="resetUserQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </div>
            </transition>

            <el-card shadow="never">
              <template #header>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button v-hasPermi="['user:user-info:add']" type="primary" plain icon="Plus" @click="handleInfoAdd">新增 </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button v-hasPermi="['user:user-info:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleInfoUpdate()"
                      >修改
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      v-hasPermi="['user:user-info:remove']"
                      type="danger"
                      plain
                      icon="Delete"
                      :disabled="multiple"
                      @click="handleInfoDelete()"
                      >删除
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button v-hasPermi="['user:user-info:export']" type="warning" plain icon="Download" @click="handleInfoExport">导出 </el-button>
                  </el-col>
                  <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
                </el-row>
              </template>

              <el-table v-loading="loading" :data="userInfoList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" show-overflow-tooltip />
                <el-table-column label="用户名" align="center" prop="userName" show-overflow-tooltip />
                <el-table-column label="性别" align="center" prop="gender" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="scope.row.gender === 1">男</template>
                    <template v-else-if="scope.row.gender === 2">女</template>
                    <template v-else>未知</template>
                  </template>
                </el-table-column>
                <el-table-column label="人员类型" align="center" prop="type" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="scope.row.type === 1">企业员工</template>
                    <template v-else-if="scope.row.type === 2">企业非常驻人员</template>
                    <template v-else-if="scope.row.type === 3">短期驻点人员</template>
                    <template v-else-if="scope.row.type === 4">来访人员</template>
                    <template v-else-if="scope.row.type === 5">黑名单人员</template>
                    <template v-else>未知</template>
                  </template>
                </el-table-column>
                <el-table-column label="证件号码" align="center" prop="idCardNo" show-overflow-tooltip />
                <el-table-column label="车牌号" align="center" prop="licensePlateNumber" show-overflow-tooltip />
                <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
                <el-table-column label="照片" align="center" prop="photo" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230">
                  <template #default="scope">
                    <el-tooltip content="修改" placement="top">
                      <el-button
                        v-hasPermi="['user:user-info:edit']"
                        link
                        type="primary"
                        icon="Edit"
                        @click="handleInfoUpdate(scope.row)"
                      ></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        v-hasPermi="['user:user-info:remove']"
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total > 0"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                :total="total"
                @pagination="getList"
              />
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 详情 添加或修改人员信息对话框 -->
    <el-drawer v-model="dialog.infoVisible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="userInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option v-for="item in genderSelect" :key="item.value" :value="item.label" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择人员类型">
            <el-option v-for="item in userTypeSelect" :key="item.value" :value="item.label" :label="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户组" prop="userGroupId">
          <el-select v-model="form.userGroupId" placeholder="请选择用户组">
            <el-option v-for="item in userGroup" :key="item.userGroupId" :value="item.userGroupId" :label="item.groupName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="证件号码" prop="idCardNo">
          <el-input v-model="form.idCardNo" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlateNumber">
          <el-input v-model="form.licensePlateNumber" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="照片" prop="photo">
          <el-input v-model="form.photo" placeholder="请输入照片" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitInfoForm">确 定</el-button>
          <el-button @click="cancelInfo">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="enterpriseInfo" lang="ts">
import {
  addenterpriseInfo,
  delenterpriseInfo,
  getenterpriseInfo,
  listenterpriseInfo,
  updateenterpriseInfo
} from '@/api/access/enterprise/enterprise-info';
import { enterpriseInfoForm, enterpriseInfoQuery, EnterpriseInfoVO } from '@/api/access/enterprise/enterprise-info/types';
import { addUserInfo, delUserInfo, getUserInfo, listUserInfo, updateUserInfo } from '@/api/access/user/user-info';
import { UserInfoVO } from '@/api/access/user/user-info/types';
import ImageUpload from '@/components/ImageUpload/index.vue';
import type { TabsPaneContext } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userInfoList = ref<UserInfoVO[]>([]);
const enterpriseInfoList = ref<EnterpriseInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const userInfoFormRef = ref<ElFormInstance>();

const queryFormRef = ref<ElFormInstance>();
const enterpriseInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  details: false,
  title: ''
});
const activeName = ref('first');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

const initFormData: enterpriseInfoForm = {
  enterpriseInfoId: undefined,
  remark: undefined,
  enterpriseName: undefined,
  uscc: undefined,
  responsiblePeople: undefined,
  telephone: undefined,
  businessLicenseImageId: undefined,
  logoImageId: undefined
};
const data = reactive<PageData<enterpriseInfoForm, enterpriseInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: undefined,
    uscc: undefined,
    responsiblePeople: undefined,
    telephone: undefined,
    params: {}
  },
  rules: {
    enterpriseInfoId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    enterpriseName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    uscc: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
    responsiblePeople: [{ required: true, message: '责任人不能为空', trigger: 'blur' }],
    telephone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    businessLicenseImageId: [{ required: true, message: '营业执照不能为空', trigger: 'change' }],
    logoImageId: [{ required: true, message: '企业LOGO不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listenterpriseInfo(queryParams.value);
  enterpriseInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.shouAdd = false;
  dialog.details = false;
  dialog.infoVisible = false;
};
/** 取消按钮 */
const cancelInfo = () => {
  reset();
  dialog.infoVisible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  enterpriseInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: EnterpriseInfoVO[]) => {
  ids.value = selection.map((item) => item.enterpriseInfoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.shouAdd = true;
  dialog.title = '添加企业信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EnterpriseInfoVO) => {
  reset();
  const _enterpriseInfoId = row?.enterpriseInfoId || ids.value[0];
  const res = await getenterpriseInfo(_enterpriseInfoId);
  Object.assign(form.value, res.data);
  dialog.shouAdd = true;
  dialog.title = '修改企业信息';
};
/** 详情按钮操作 */
const handleDetails = async (row?: EnterpriseInfoVO) => {
  reset();
  const _enterpriseInfoId = row?.enterpriseInfoId || ids.value[0];
  const res = await getenterpriseInfo(_enterpriseInfoId);
  Object.assign(form.value, res.data);
  dialog.details = true;
  dialog.title = '详情';
  getUserList();
};

/** 详情 人员信息列表 */
const getUserList = async () => {
  loading.value = true;
  const res = await listUserInfo(queryParams.value);
  userInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 详情 搜索按钮操作 */
const handleUserQuery = () => {
  queryParams.value.pageNum = 1;
  getUserList();
};

/** 详情 重置按钮操作 */
const resetUserQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 详情 删除按钮操作 */
const handleInfoDelete = async (row?: UserInfoVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除人员信息编号为"' + _userIds + '"的数据项？').finally(() => (loading.value = false));
  await delUserInfo(_userIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
/** 详情 提交按钮 */
const submitInfoForm = () => {
  userInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.userId) {
        await updateUserInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.shouAdd = false;
      await getList();
    }
  });
};
/** 详情 导出按钮操作 */
const handleInfoExport = () => {
  proxy?.download(
    'user/userInfo/export',
    {
      ...queryParams.value
    },
    `userInfo_${new Date().getTime()}.xlsx`
  );
};

/** 新增按钮操作 */
const handleInfoAdd = () => {
  reset();
  dialog.infoVisible = true;
  dialog.title = '添加人员信息';
};

/** 修改按钮操作 */
const handleInfoUpdate = async (row?: UserInfoVO) => {
  reset();
  const _userId = row?.userId || ids.value[0];
  const res = await getUserInfo(_userId);
  Object.assign(form.value, res.data);
  dialog.infoVisible = true;
  dialog.title = '修改人员信息';
};

/** 提交按钮 */
const submitForm = () => {
  enterpriseInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.enterpriseInfoId) {
        await updateenterpriseInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addenterpriseInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.shouAdd = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EnterpriseInfoVO) => {
  const _enterpriseInfoIds = row?.enterpriseInfoId || ids.value;
  await proxy?.$modal.confirm('是否确认删除企业信息编号为"' + _enterpriseInfoIds + '"的数据项？').finally(() => (loading.value = false));
  await delenterpriseInfo(_enterpriseInfoIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'enterprise/enterprise-info/export',
    {
      ...queryParams.value
    },
    `enterprise-info_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-card__header) {
  height: 60px;
}

:deep(.el-card__body) {
  height: calc(100% - 60px);
}

:deep(.pagination-container) {
  margin-top: 0;
}
</style>
